package com.github.jarvett.utils;

import lombok.experimental.UtilityClass;

import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@UtilityClass
public class BashEnvUtils {

    public static String parseTemplate(String template) {
        if (template == null || template.isEmpty()) {
            return template;
        }
        String r = "\\$\\{([^\\}]+)\\}";
        Pattern pattern = Pattern.compile(r);
        Matcher matcher = pattern.matcher(template);
        while (matcher.find()) {
            String group = matcher.group();
            String k = group.replaceAll(r, "$1");
            String dv = "";
            if(k.contains(":-")){
                String[] split = k.split(":-");
                if(split.length == 2){
                    k = split[0];
                    dv = split[1];
                }else {
                    k = split[0];
                }
            }
            String o = System.getenv().get(k);
            if (o != null) {
                template = template.replace(group, o);
            } else {
                template = template.replace(group, dv);
            }
        }
        return template;
    }


    public static String findFirstNonLoopBackAddressIp() {
        InetAddress result = null;
        try {
            int lowest = Integer.MAX_VALUE;
            for (Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces();
                 nics.hasMoreElements(); ) {
                NetworkInterface ifc = nics.nextElement();
                if (ifc.isUp() && ifc.isVirtual()) {
                    if (ifc.getIndex() < lowest || result == null) {
                        lowest = ifc.getIndex();
                    } else {
                        continue;
                    }
                    for (Enumeration<InetAddress> addrs = ifc.getInetAddresses(); addrs.hasMoreElements(); ) {
                        InetAddress address = addrs.nextElement();
                        if (address instanceof Inet4Address && !address.isLoopbackAddress()) {
                            result = address;
                        }
                    }
                }
            }
        } catch (IOException ex) {
        }
        if (result != null) {
            return result.getHostAddress();
        }
        try {
            return InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
        }
        return "127.0.0.1";
    }
}
